//
//  LROAuthVC.swift
//  WeiboX
//
//  Created by admin on 02/12/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit
import SVProgressHUD

let appKey: String = "2158635023"
let redirect_uri: String = "http://www.jianshu.com"
let appSecret: String = "ae9870623b24b3de143017082b6ca979"

class LROAuthVC: UIViewController {
	
	lazy var webView: UIWebView = UIWebView()
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		// Do any additional setup after loading the view.
		setupNavUI()
		loadRequest()
	}
	
	override func loadView() {
		
		webView.delegate = self
		view = webView
	}
	
	private func loadRequest() {
		// https://api.weibo.com/oauth2/authorize?client_id=2158635023&redirect_uri=http://www.jianshu.com
		
		let urlStr: String = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirect_uri)"
//		print(urlStr)
		let urlRequest: URLRequest = URLRequest(url: URL.init(string: urlStr)!)
		
		webView.loadRequest(urlRequest)
	}
	
	private func setupNavUI() {
		webView.isOpaque = false
		
		navigationItem.title = "微博登录"
		navigationItem.leftBarButtonItem = UIBarButtonItem(title: "cancel", target: self, action: #selector(cancelBtnAction))
		navigationItem.rightBarButtonItem = UIBarButtonItem(title: "autoFill", target: self, action: #selector(autoFillBtnAction))
	}
	
	@objc private func cancelBtnAction() {
		dismiss(animated: true, completion: nil)
	}
	
	@objc private func autoFillBtnAction() {
		webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '553842250@qq.com';document.getElementById('passwd').value = 'wyqdsb2014'")
	}
	

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension LROAuthVC: UIWebViewDelegate {
	
	func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
		guard let url = request.url else {
			return false
		}
		// http://www.jianshu.com/?code=ad8e8e675a35b753582c8fef68d7c5a2
		if !url.absoluteString.hasPrefix(redirect_uri) {
			return true
		}
		
		if let query = url.query, query.hasPrefix("code=") {
			let startIndex = "code=".endIndex
			let code = query.substring(from: startIndex)
			
			print(code)
			
			LRUserAccountVM.sharedUserAccount.requestAccessToken(code: code, callBack: { (isSuccess) in
				if isSuccess {
					print("登录成功")
					
					
					
					self.dismiss(animated: true, completion: {
						NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotifacationName), object: self)
					})
					
				} else {
					print("失败")
				}
			})
		}
		
		return false
	}
	
	
	func webViewDidStartLoad(_ webView: UIWebView) {
		SVProgressHUD.show()
	}
	
	func webViewDidFinishLoad(_ webView: UIWebView) {
		SVProgressHUD.dismiss()
	}
	
	func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
		SVProgressHUD.dismiss()
	}
}

